// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import FastClick from 'fastclick'
import { sync } from 'vuex-router-sync'
import { cookie } from 'vux'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false
sync(store, router);

if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', () => {
        FastClick.attach(document.body);
    }, false)
}

const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
let isPush = false
let endTime = Date.now()
let methods = ['push', 'go', 'replace', 'forward', 'back']

router.beforeEach((to, from, next) => {
    const toIndex = history.getItem(to.path)
    const fromIndex = history.getItem(from.path)
    if (toIndex) {
        if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
          store.commit('APP_UPDATE_DIRECTION', {direction: 'forward'})
        } else {
          // 判断是否是ios左滑返回
          if (!isPush && (Date.now() - endTime) < 377) {
            store.commit('APP_UPDATE_DIRECTION', {direction: ''})
          } else {
            store.commit('APP_UPDATE_DIRECTION', { direction: 'reverse' })
          }
        }
    } else {
        ++historyCount
        history.setItem('count', historyCount)
        to.path !== '/' && history.setItem(to.path, historyCount)
        store.commit('APP_UPDATE_DIRECTION', {direction: 'forward'})
    }

    let userId = cookie.get('userId');
    if (to.meta.auth === true && !userId) {
        return next('/auth?redirect=' + encodeURIComponent(to.path || '/'));
    } else {
        next();
    }
});
router.afterEach((transition,to) => {
    if (transition.meta.title) {
        document.title = transition.meta.title;
        var body = document.getElementsByTagName('body')[0];
        var iframe = document.createElement("iframe");
        iframe.title = transition.meta.title;
        iframe.width = 0;
        iframe.height = 0;
        iframe.style.display = 'none'
        document.body.appendChild(iframe)
        iframe.addEventListener('load', function() {
            setTimeout(function() {
                iframe.removeEventListener('load', function() {})
                document.body.removeChild(iframe)
            }, 0)
        });
    }
});
/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})